package com.hk.Mgr.web.controller;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.base.ResponseBase;
import com.hk.commons.HqlFilter;
import com.hk.commons.ResultCode;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.utils.sys.DateWeekOrHoliday;
import com.hk.commons.utils.yingmi.YingmiApiUtils;
import com.hk.service.sys.ISysUser;

@Controller
public class YesterDayProfitCtrl {
	private Logger logger = LoggerFactory.getLogger(YesterDayProfitCtrl.class);


	@Autowired
	private ISysUser sysUserService;

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Autowired
	private YingmiApiUtils utils;

	/**
	 * @Title: getCustomerById
	 * @Description: 根据id获取系统模块信息
	 * @param
	 */

	@ResponseBody
	@RequestMapping(value = "/getYestProfit", produces = "application/json;charset=UTF8", method = RequestMethod.GET)
	public ResponseBase<String> getYestProfit(@RequestParam String userId) {
		userId = userId.split(",")[0];
		ResponseBase<String> resp = new ResponseBase<String>();
		BigDecimal yestAllProfit = new BigDecimal(0);

		List<SysUser> userList = qryUser(userId);
		if (userList.size() > 0) {
			SysUser user = userList.get(0);
			try {
				/* 查询固收 */
				BigDecimal hcOurYesProfit = getHuoChaiAndOur(user);
				logger.info("固定收益hcOurYesProfit={},userId={}", hcOurYesProfit,
						userId);
				yestAllProfit = yestAllProfit.add(hcOurYesProfit);
			} catch (Exception e) {
				logger.info("查询固定资产昨日收益异常,userId={}", userId);
				logger.error("<-------------------------ERROR---------------------->", e);
			}
			
			if (user.getAccountId() != null) {
				/* 查询基金 */
				try {
					BigDecimal fundYestProfit = getymFunds(user);
					logger.info("基金收益：fundYestProfit={},userId={}",
							fundYestProfit, userId);
					yestAllProfit = yestAllProfit.add(fundYestProfit);
				} catch (Exception e) {
					logger.info("查询基金昨日收益异常,userId={}", userId);
					logger.error("<-------------------------ERROR---------------------->", e);
				}

				/* 查询盈米宝 */
				try {
					BigDecimal ymbYesProfit = getYMB(user);
					logger.info("盈米宝收益：ymbYesProfit={},userId={}",
							ymbYesProfit, userId);
					yestAllProfit = yestAllProfit.add(ymbYesProfit);
				} catch (Exception e) {
					logger.info("查询盈米宝昨日收益异常,userId={}", userId);
					logger.error("<-------------------------ERROR---------------------->", e);
				}

			} else {
				logger.info("accountId为空！无法查询基金：accountId={},userId={}",
						user.getAccountId(), userId);
			}

			yestAllProfit = yestAllProfit.setScale(2, BigDecimal.ROUND_HALF_UP);// 0.00001为0.01
			resp.setMsg("成功");
			resp.setResult(String.valueOf(yestAllProfit.toString()));
			resp.setResultCode(ResultCode.SUCC.getCode());
		} else {
			logger.info("YesterDayProfitCtrl->getYestProfit查询不到客户!userId={}",
					userId);
			resp.setResultCode(ResultCode.FAILED.getCode());
			resp.setMsg("查询不到客户");
			resp.setResult("0.00");

		}

		return resp;
	}

	/* 查询固定收益类产品：火柴和自有产品 */
	private BigDecimal getHuoChaiAndOur(SysUser user) {// 今天之前的收益
		BigDecimal profit=BigDecimal.valueOf(0);
		String sql="select orderId,orderTradeDate,dividendDate,proTerm,prodDividend,extraTerm,extraDividend from orderView where payStatus=2 and confirmStatus=2 and userId="+user.getId();
		List<Map<String, Object>> resultListMap=jdbcTemplate.queryForList(sql);
		if(resultListMap!=null&&resultListMap.size()>0){
			for(Map<String, Object> map:resultListMap){				
				Long orderTradeDate=(Long) map.get("orderTradeDate");
				if(orderTradeDate!=null&&orderTradeDate.longValue()!=0L){
					Date profitDate = new Date(orderTradeDate);
					Calendar beginProficC = Calendar.getInstance();
					beginProficC.setTime(profitDate);
					Calendar nowCalendar = Calendar.getInstance();
					// 计息时间在今天或之后则无利息。
					if (DateWeekOrHoliday.ifLongger(beginProficC, nowCalendar)) {
						logger.info("YesterDayProfitCtrl->getHuoChaiAndOur未开始计息");
					} else {// 计息时间在今天之前则已经开始产生收益
						Long dividendDate=(Long) map.get("dividendDate");
						Long orderId=(Long) map.get("orderId");
						if (dividendDate != null&&dividendDate.longValue()!=0L) {
							Date finalDate = new Date(dividendDate);
							Calendar finalCalendar = Calendar
									.getInstance();
							finalCalendar.setTime(finalDate);
							if (DateWeekOrHoliday.ifLongger(
									finalCalendar, nowCalendar)
									|| DateWeekOrHoliday
											.afterDay(
													finalCalendar,
													nowCalendar)) {
								BigDecimal proDividend=(BigDecimal) map.get("prodDividend");
								BigDecimal extraDividend=map.get("extraDividend")==null?BigDecimal.valueOf(0):(BigDecimal) map.get("extraDividend");
								int proTerm=(int) map.get("proTerm");							
								int extraTerm=(map.get("extraTerm")==null?proTerm:(int) map.get("extraTerm"));
								extraTerm=extraTerm==0?proTerm:extraTerm;
								profit = profit.add(getProductProfit( proDividend, proTerm)).add(getExtraProfit(extraDividend,extraTerm,beginProficC,nowCalendar));								
							}
						} else {
							logger.info(
									"此订单还本到期日为空。orderId={}",
									orderId);
						}
					}
				}								
			}
		}		
		return profit;
	}

	
	private BigDecimal getProductProfit(BigDecimal proDividend,int term){
		if(term==0){
			return BigDecimal.valueOf(0);
		}else{
			return proDividend.divide(new BigDecimal(term),6,BigDecimal.ROUND_HALF_DOWN);
		}		
	}
	
	private BigDecimal getExtraProfit(BigDecimal extraDividend,int term,Calendar beginProficC,Calendar nowCalendar){
		if(term==0){
			return BigDecimal.valueOf(0);
		}else{
			Calendar addExtraTermDay=beginProficC;
			addExtraTermDay.add(Calendar.DAY_OF_YEAR, term);
			if(DateWeekOrHoliday.ifLongger(addExtraTermDay, nowCalendar)){// 加息券到期时间在今天或之后则无利息。
				return extraDividend.divide(new BigDecimal(term),6,BigDecimal.ROUND_HALF_DOWN);
			}else{
				return BigDecimal.valueOf(0);
			}			
		}
	}
	
	/* 查询客户在盈米的基金 */
	private BigDecimal getymFunds(SysUser user) {
		BigDecimal fundYesProfit = new BigDecimal(0);
		Map<String, String> params = new HashMap<>();
		params.put("brokerUserId", user.getName());
		params.put("accountId", user.getAccountId());
		String fundsList = utils.get("/trade/getFundShares", params);
		if ((!fundsList.contains("msg")) && (!"{}".equals(fundsList))) {
			JSONArray resultArray = new JSONArray(fundsList);
			for (int i = 0; i < resultArray.length(); i++) {
				JSONObject objectStr = resultArray.getJSONObject(i);
				String previousProfit = objectStr.get("previousProfit")
						.toString();
				if (StringHelper.isNotEmpty(previousProfit)) {
					fundYesProfit = fundYesProfit.add(new BigDecimal(
							previousProfit));
				}
			}
		} else {
			logger.info(
					"QueryDayProfitsController->getymFunds()->基金理财获取错误或改用户没有基金理财信息,userId={}",
					user.getId());

		}
		return fundYesProfit;
	}

	/* 查询基金昨日收益 */
	private BigDecimal qryDayShouyi(SysUser user, String fundCodes) {
		BigDecimal fundYesProfit = new BigDecimal(0);
		Map<String, String> params = new HashMap<>();
		params.put("brokerUserId", user.getName());
		params.put("accountId", user.getAccountId()); 
		// 查询盈米宝
		if (!StringHelper.isEmpty(fundCodes)) {
			params.put("fundCode", fundCodes);
		}
		String shouyi = utils.get("/trade/getProfits", params);
		if ((!shouyi.contains("msg")) && (!"{}".equals(shouyi))) {
			JSONObject profitJsonObject = new JSONObject(shouyi);
			Iterator<String> it = profitJsonObject.keys();
			while (it.hasNext()) {
				String key = (String) it.next();
				JSONArray array = new JSONArray(profitJsonObject.get(key)
						.toString());
				for (int i = 0; i < array.length(); i++) {
					JSONObject curJsonObject = array.getJSONObject(i);
					BigDecimal aa = new BigDecimal(
							curJsonObject.getString("profit"));
					fundYesProfit = fundYesProfit.add(aa);
				}
			}
		} else {
			logger.info(
					"YesterDayProfitCtrl->qryDayShouyi()->查询盈亏记录错误或该用户没有盈亏记录-brokerUserId={}",
					user.getName());
		}
		return fundYesProfit;
	}

	/* 查询盈米宝（华康宝）信息 */
	private BigDecimal getYMB(SysUser user) {
		Map<String, String> params = new HashMap<>();
		params.put("brokerUserId", user.getName());
		params.put("accountId", user.getAccountId());
		String fundsList = utils.get("/trade/getWalletShares", params);
		BigDecimal zxsy = new BigDecimal(0);// 最新收益
		if ((!fundsList.contains("msg")) && (!"{}".equals(fundsList))) {
			JSONArray resultArray = new JSONArray(fundsList);
			for (int i = 0; i < resultArray.length(); i++) {
				JSONObject obj = resultArray.getJSONObject(i);
				String fundCode = obj.getString("fundCode");
				BigDecimal zxShouyi = qryDayShouyi(user, fundCode);
				zxsy = zxsy.add(zxShouyi);
			}
		} else {
			logger.info(
					"YesterDayProfitCtrl->getYMB()->华康宝信息获取错误或该用户没有盈米宝信息brokerUserId={},accountId={}",
					user.getName(), user.getAccountId());
		}
		return zxsy;
	}

	private List<SysUser> qryUser(String userId) {
		List<SysUser> userList = null;
		HqlFilter sysHqlFilter = new HqlFilter();
		sysHqlFilter.addEQFilter("Id", userId);
		userList = sysUserService.findByFilter(sysHqlFilter);
		return userList;
	}

}
